package com.starblink.android.basic.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.text.LineBreaker
import android.os.Build
import android.text.Layout
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.widget.addTextChangedListener

/**
 *  Create by yuanl at 2023/10/12
 **/
class EasyClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    styleTheme: Int = 0
) : AppCompatEditText(context, attrs, styleTheme) {

    private val endDrawable: Drawable? = compoundDrawables[2]

    var onClearListener: OnClearListener? = null

    init {
        isFocusable = true
        isFocusableInTouchMode = true
        isAllCaps = false

        val detector =
            GestureDetector(this.context, object : GestureDetector.SimpleOnGestureListener() {

                override fun onSingleTapUp(e: MotionEvent): Boolean {
                    val icon = compoundDrawables[2]
                    if (icon != null && e.x > width - icon.intrinsicWidth - this@EasyClearEditText.paddingRight) {
                        if ((text?.length ?: 0) > 0) {
                            text = null
                            onClearListener?.invoke()
                        }
                        return true
                    }
                    return super.onSingleTapUp(e)
                }

            })

        setOnTouchListener { _, event ->
            detector.onTouchEvent(event)
        }

        addTextChangedListener(
            afterTextChanged = {
                switchIcon()
            }
        )
        switchIcon()
    }

    private fun switchIcon() {
        val icon = if ((text?.length
                ?: 0) > 0
        ) endDrawable else null
        setCompoundDrawables(
            compoundDrawables[0],
            compoundDrawables[1],
            icon,
            compoundDrawables[3]
        )
    }

}

typealias OnClearListener = () -> Unit